package org.javaboy.vhr.bim.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.banboocloud.Codec.BamboocloudFacade;
import org.javaboy.vhr.bim.entity.AttributeEntity;
import org.javaboy.vhr.bim.utils.BamboocloudUtils;
import org.javaboy.vhr.bim.utils.JacksonUtil;
import org.javaboy.vhr.model.*;
import org.javaboy.vhr.service.DepartmentService;
import org.javaboy.vhr.service.EmployeeService;
import org.javaboy.vhr.service.PositionService;
import org.javaboy.vhr.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("bimService")
public class BIMController {

    @Autowired
    private EmployeeService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService deptService;
    @Autowired
    private PositionService positionService;

    @RequestMapping("hello")
    public String hello() {
        return "hello";
    }
    public Map<String, Object> checkRequest(HttpServletRequest request){
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("checkPass",false);
        resultMap.put("reqMap","");
        resultMap.put("errorMsgStr","");
        String requestBody= BamboocloudUtils.getRequestBody(request);
        //解密json字符传
        requestBody = BamboocloudUtils.getPlaintext(requestBody, "123456", "AES");
        Map<String, Object> reqMap = (Map<String, Object>) JSONUtils.parse(requestBody);
        resultMap.put("reqMap",reqMap);
        boolean checkPass = false;
        if (BamboocloudUtils.verify(reqMap, "MD5").booleanValue()){
            String username = (String) reqMap.get("bimRemoteUser");
            String password = (String) reqMap.get("bimRemotePwd");
            //判断接口中的调用名及调用密码是否正确
            if (BamboocloudUtils.checkUsernamePassword(username, password)) {
                checkPass = true;
            }
        }
        if(!checkPass){
            String resultStr = "";
            JSONObject resultObj = new JSONObject();
            resultObj.put("bimRequestId","");
            resultObj.put("resultCode","505");
            resultObj.put("message","连接失败,请检查连接器配置的参数");
            resultStr = JSONUtils.toJSONString(resultObj);
            //返回加密的json字符串
            resultStr = BamboocloudFacade.encrypt(resultStr, "123456", "AES");
            resultMap.put("errorMsgStr",resultStr);
        }
        resultMap.put("checkPass",checkPass);
        return resultMap;
    }

    @RequestMapping("SchemaService")
    public String schema(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }

        Map<String, Object> schema = new HashMap<>();
        List<AttributeEntity> accountAttrList = new ArrayList<>();
        AttributeEntity useridAttribute = new AttributeEntity();
        useridAttribute.setType("String");
        useridAttribute.setName("id");
        useridAttribute.setRequired(true);
        useridAttribute.setMultivalued(false);
        accountAttrList.add(useridAttribute);
        AttributeEntity usernameAttribute = new AttributeEntity();
        usernameAttribute.setType("String");
        usernameAttribute.setName("name");
        usernameAttribute.setRequired(true);
        usernameAttribute.setMultivalued(false);
        accountAttrList.add(usernameAttribute);
        AttributeEntity usergenderAttribute = new AttributeEntity();
        usergenderAttribute.setType("String");
        usergenderAttribute.setName("gender");
        usergenderAttribute.setRequired(true);
        usergenderAttribute.setMultivalued(false);
        accountAttrList.add(usergenderAttribute);
        AttributeEntity userbirthdayAttribute = new AttributeEntity();
        userbirthdayAttribute.setType("String");
        userbirthdayAttribute.setName("birthday");
        userbirthdayAttribute.setRequired(true);
        userbirthdayAttribute.setMultivalued(false);
        accountAttrList.add(userbirthdayAttribute);
        AttributeEntity useridCardAttribute = new AttributeEntity();
        useridCardAttribute.setType("String");
        useridCardAttribute.setName("idCard");
        useridCardAttribute.setRequired(true);
        useridCardAttribute.setMultivalued(false);
        accountAttrList.add(useridCardAttribute);
        AttributeEntity userwedlockAttribute = new AttributeEntity();
        userwedlockAttribute.setType("String");
        userwedlockAttribute.setName("wedlock");
        userwedlockAttribute.setRequired(true);
        userwedlockAttribute.setMultivalued(false);
        accountAttrList.add(userwedlockAttribute);
        AttributeEntity usernationIdAttribute = new AttributeEntity();
        usernationIdAttribute.setType("String");
        usernationIdAttribute.setName("nationId");
        usernationIdAttribute.setRequired(true);
        usernationIdAttribute.setMultivalued(false);
        accountAttrList.add(usernationIdAttribute);
        AttributeEntity usernativePlaceAttribute = new AttributeEntity();
        usernativePlaceAttribute.setType("String");
        usernativePlaceAttribute.setName("nativePlace");
        usernativePlaceAttribute.setRequired(true);
        usernativePlaceAttribute.setMultivalued(false);
        accountAttrList.add(usernativePlaceAttribute);
        AttributeEntity userpoliticIdAttribute = new AttributeEntity();
        userpoliticIdAttribute.setType("String");
        userpoliticIdAttribute.setName("politicId");
        userpoliticIdAttribute.setRequired(true);
        userpoliticIdAttribute.setMultivalued(false);
        accountAttrList.add(userpoliticIdAttribute);
        AttributeEntity useremailAttribute = new AttributeEntity();
        useremailAttribute.setType("String");
        useremailAttribute.setName("email");
        useremailAttribute.setRequired(true);
        useremailAttribute.setMultivalued(false);
        accountAttrList.add(useremailAttribute);
        AttributeEntity userphoneAttribute = new AttributeEntity();
        userphoneAttribute.setType("String");
        userphoneAttribute.setName("phone");
        userphoneAttribute.setRequired(true);
        userphoneAttribute.setMultivalued(false);
        accountAttrList.add(userphoneAttribute);
        AttributeEntity useraddressAttribute = new AttributeEntity();
        useraddressAttribute.setType("String");
        useraddressAttribute.setName("address");
        useraddressAttribute.setRequired(true);
        useraddressAttribute.setMultivalued(false);
        accountAttrList.add(useraddressAttribute);
        AttributeEntity userdepartmentIdAttribute = new AttributeEntity();
        userdepartmentIdAttribute.setType("String");
        userdepartmentIdAttribute.setName("departmentId");
        userdepartmentIdAttribute.setRequired(true);
        userdepartmentIdAttribute.setMultivalued(false);
        accountAttrList.add(userdepartmentIdAttribute);
        AttributeEntity userjobLevelIdAttribute = new AttributeEntity();
        userjobLevelIdAttribute.setType("String");
        userjobLevelIdAttribute.setName("jobLevelId");
        userjobLevelIdAttribute.setRequired(true);
        userjobLevelIdAttribute.setMultivalued(false);
        accountAttrList.add(userjobLevelIdAttribute);
        AttributeEntity userposIdAttribute = new AttributeEntity();
        userposIdAttribute.setType("String");
        userposIdAttribute.setName("posId");
        userposIdAttribute.setRequired(true);
        userposIdAttribute.setMultivalued(false);
        accountAttrList.add(userposIdAttribute);
        AttributeEntity userengageFormAttribute = new AttributeEntity();
        userengageFormAttribute.setType("String");
        userengageFormAttribute.setName("engageForm");
        userengageFormAttribute.setRequired(true);
        userengageFormAttribute.setMultivalued(false);
        accountAttrList.add(userengageFormAttribute);
        AttributeEntity usertiptopDegreeAttribute = new AttributeEntity();
        usertiptopDegreeAttribute.setType("String");
        usertiptopDegreeAttribute.setName("tiptopDegree");
        usertiptopDegreeAttribute.setRequired(true);
        usertiptopDegreeAttribute.setMultivalued(false);
        accountAttrList.add(usertiptopDegreeAttribute);
        AttributeEntity userspecialtyAttribute = new AttributeEntity();
        userspecialtyAttribute.setType("String");
        userspecialtyAttribute.setName("specialty");
        userspecialtyAttribute.setRequired(true);
        userspecialtyAttribute.setMultivalued(false);
        accountAttrList.add(userspecialtyAttribute);
        AttributeEntity userschoolAttribute = new AttributeEntity();
        userschoolAttribute.setType("String");
        userschoolAttribute.setName("school");
        userschoolAttribute.setRequired(true);
        userschoolAttribute.setMultivalued(false);
        accountAttrList.add(userschoolAttribute);
        AttributeEntity userbeginDateAttribute = new AttributeEntity();
        userbeginDateAttribute.setType("String");
        userbeginDateAttribute.setName("beginDate");
        userbeginDateAttribute.setRequired(true);
        userbeginDateAttribute.setMultivalued(false);
        accountAttrList.add(userbeginDateAttribute);
        AttributeEntity userworkStateAttribute = new AttributeEntity();
        userworkStateAttribute.setType("String");
        userworkStateAttribute.setName("workState");
        userworkStateAttribute.setRequired(true);
        userworkStateAttribute.setMultivalued(false);
        accountAttrList.add(userworkStateAttribute);
        AttributeEntity userworkIDAttribute = new AttributeEntity();
        userworkIDAttribute.setType("String");
        userworkIDAttribute.setName("workID");
        userworkIDAttribute.setRequired(true);
        userworkIDAttribute.setMultivalued(false);
        accountAttrList.add(userworkIDAttribute);
        AttributeEntity usercontractTermAttribute = new AttributeEntity();
        usercontractTermAttribute.setType("String");
        usercontractTermAttribute.setName("contractTerm");
        usercontractTermAttribute.setRequired(true);
        usercontractTermAttribute.setMultivalued(false);
        accountAttrList.add(usercontractTermAttribute);
        AttributeEntity userconversionTimeAttribute = new AttributeEntity();
        userconversionTimeAttribute.setType("String");
        userconversionTimeAttribute.setName("conversionTime");
        userconversionTimeAttribute.setRequired(true);
        userconversionTimeAttribute.setMultivalued(false);
        accountAttrList.add(userconversionTimeAttribute);
        AttributeEntity userbeginContractAttribute = new AttributeEntity();
        userbeginContractAttribute.setType("String");
        userbeginContractAttribute.setName("beginContract");
        userbeginContractAttribute.setRequired(true);
        userbeginContractAttribute.setMultivalued(false);
        accountAttrList.add(userbeginContractAttribute);
        AttributeEntity userendContractAttribute = new AttributeEntity();
        userendContractAttribute.setType("String");
        userendContractAttribute.setName("endContract");
        userendContractAttribute.setRequired(true);
        userendContractAttribute.setMultivalued(false);
        accountAttrList.add(userendContractAttribute);
        AttributeEntity usernationAttribute = new AttributeEntity();
        usernationAttribute.setType("String");
        usernationAttribute.setName("nation");
        usernationAttribute.setRequired(true);
        usernationAttribute.setMultivalued(true);
        accountAttrList.add(usernationAttribute);
        AttributeEntity userpoliticsstatusAttribute = new AttributeEntity();
        userpoliticsstatusAttribute.setType("String");
        userpoliticsstatusAttribute.setName("politicsstatus");
        userpoliticsstatusAttribute.setRequired(true);
        userpoliticsstatusAttribute.setMultivalued(true);
        accountAttrList.add(userpoliticsstatusAttribute);
        AttributeEntity userdepartmentAttribute = new AttributeEntity();
        userdepartmentAttribute.setType("String");
        userdepartmentAttribute.setName("department");
        userdepartmentAttribute.setRequired(true);
        userdepartmentAttribute.setMultivalued(true);
        accountAttrList.add(userdepartmentAttribute);
        AttributeEntity userjobLevelAttribute = new AttributeEntity();
        userjobLevelAttribute.setType("String");
        userjobLevelAttribute.setName("jobLevel");
        userjobLevelAttribute.setRequired(true);
        userjobLevelAttribute.setMultivalued(true);
        accountAttrList.add(userjobLevelAttribute);
        AttributeEntity userpositionAttribute = new AttributeEntity();
        userpositionAttribute.setType("String");
        userpositionAttribute.setName("position");
        userpositionAttribute.setRequired(true);
        userpositionAttribute.setMultivalued(true);
        accountAttrList.add(userpositionAttribute);

        List<AttributeEntity> organizationList = new ArrayList<AttributeEntity>();
        AttributeEntity org1 = new AttributeEntity();
        org1.setType("Integer");
        org1.setName("id");
        org1.setRequired(false);
        org1.setMultivalued(false);
        organizationList.add(org1);
        AttributeEntity org2 = new AttributeEntity();
        org2.setType("Long");
        org2.setName("parentId");
        org2.setRequired(false);
        org2.setMultivalued(false);
        organizationList.add(org2);
        AttributeEntity org4 = new AttributeEntity();
        org4.setType("String");
        org4.setName("name");
        org4.setRequired(false);
        org4.setMultivalued(false);
        organizationList.add(org4);
        AttributeEntity org5 = new AttributeEntity();
        org5.setType("String");
        org5.setName("depPath");
        org5.setRequired(false);
        org5.setMultivalued(false);
        organizationList.add(org5);
        AttributeEntity org6 = new AttributeEntity();
        org6.setType("Boolean");
        org6.setName("enabled");
        org6.setRequired(false);
        org6.setMultivalued(false);
        organizationList.add(org6);
        AttributeEntity org7 = new AttributeEntity();
        org7.setType("Boolean");
        org7.setName("parent");
        org7.setRequired(false);
        org7.setMultivalued(false);
        organizationList.add(org7);


        List<AttributeEntity> roleList = new ArrayList<AttributeEntity>();
        AttributeEntity role1 = new AttributeEntity();
        role1.setType("Long");
        role1.setName("id");
        role1.setRequired(false);
        role1.setMultivalued(false);
        roleList.add(role1);
        AttributeEntity role2 = new AttributeEntity();
        role2.setType("String");
        role2.setName("name");
        role2.setRequired(false);
        role2.setMultivalued(false);
        roleList.add(role2);
        AttributeEntity role3 = new AttributeEntity();
        role3.setType("String");
        role3.setName("nameZh");
        role3.setRequired(false);
        role3.setMultivalued(false);
        roleList.add(role3);

        List<AttributeEntity> positionList = new ArrayList<AttributeEntity>();
        AttributeEntity position1 = new AttributeEntity();
        position1.setType("Integer");
        position1.setName("id");
        position1.setRequired(false);
        position1.setMultivalued(false);
        positionList.add(position1);
        AttributeEntity position2 = new AttributeEntity();
        position2.setType("String");
        position2.setName("name");
        position2.setRequired(false);
        position2.setMultivalued(false);
        positionList.add(position2);

        schema.put("account", accountAttrList);
        schema.put("organization", organizationList);
        schema.put("role", roleList);
        schema.put("position", positionList);

        String resultStr = JacksonUtil.toJson(schema);
        //返回加密的json字符串
        resultStr = BamboocloudFacade.encrypt(resultStr, "123456", "AES");
        return resultStr;
    }

//    @RequestMapping("UserDeleteService")
//    public String userDelete(@RequestBody Map reqmap) {
//        userService.deleteEmpByEid(Integer.parseInt(Objects.toString(reqmap.get("bimUid"), "")));
//        Map<String, Object> schema = new HashMap<String, Object>();
//        schema.put("bimRequestId", reqmap.get("bimRequestId"));
//        schema.put("resultCode", "0");
//        schema.put("message", "success");
//        String mapJson = JacksonUtil.toJson(schema);
//        return mapJson;
//    }

    @RequestMapping("QueryAllUserIdsService")
    public String queryAllUserIds(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }

        Employee user = new Employee();
        RespPageBean respPageBean = userService.getEmployeeByPage(1, Integer.MAX_VALUE, user, null);
        List userList = respPageBean.getData();
        List uids = new ArrayList();
        for (int i = 0; i < userList.size(); i++) {
            uids.add(((Employee) userList.get(i)).getId());
        }
        Map<String, Object> schema = new HashMap<String, Object>();
        schema.put("resultCode", "0");
        schema.put("userIdList", uids);
        schema.put("message", "success");
        String mapJson = JacksonUtil.toJson(schema);
        mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
        return mapJson;
    }

    @RequestMapping("QueryUserByIdService")
    public String queryUserById(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }

        Map<String, Object> reqMap = (Map<String, Object>)checkResult.get("reqMap");
        String userId = Objects.toString(reqMap.get("bimUid"));
        Employee user = userService.getEmployeeById(Integer.parseInt(userId));

        Map<String, Object> schema = new HashMap<>();
        schema.put("bimRequestId", reqMap.get("bimRequestId"));
        schema.put("resultCode", "0");
        schema.put("account", user);
        schema.put("message", "success");
        String mapJson = JacksonUtil.toJson(schema);
        mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
        return mapJson;
    }

//    @RequestMapping("orgDeleteService")
//    public String orgDelete(@RequestBody Map reqmap) {
//        Department department = new Department();
//        department.setId(Integer.parseInt(Objects.toString(reqmap.get("bimOrgId"), "")));
//        deptService.deleteDepById(department);
//        Map<String, Object> schema = new HashMap<String, Object>();
//        schema.put("bimRequestId", reqmap.get("bimRequestId"));
//        schema.put("resultCode", "0");
//        schema.put("message", "success");
//        String mapJson = JacksonUtil.toJson(schema);
//        return mapJson;
//    }

    //
    @RequestMapping("QueryAllOrgIdsService")
    public String queryAllOrgIds(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }

        List<Department> depts = deptService.getAllDepartmentsWithOutChildren();
        List<String> uids = new ArrayList<>();
        for (int i = 0; i < depts.size(); i++) {
            uids.add(String.valueOf(depts.get(i).getId()));
        }
        Map<String, Object> schema = new HashMap<>();
        schema.put("resultCode", "0");
        schema.put("orgIdList", uids);
        schema.put("message", "success");
        String mapJson = JacksonUtil.toJson(schema);
        mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
        return mapJson;
    }

    @RequestMapping("QueryOrgByIdService")
    public String queryOrgById(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }
        Map<String, Object> reqMap = (Map<String, Object>)checkResult.get("reqMap");
        String orgId = Objects.toString(reqMap.get("bimUid"));
        Department dept = deptService.getDepById(Integer.parseInt(orgId));
        DepartmentForBim departmentForBim = new DepartmentForBim();
        BeanUtils.copyProperties(dept,departmentForBim);
        Map<String, Object> schema = new HashMap<String, Object>();
        schema.put("bimRequestId", reqMap.get("bimRequestId"));
        schema.put("resultCode", "0");
        schema.put("organization", departmentForBim);
        schema.put("message", "success");
        String mapJson = JacksonUtil.toJson(schema);
        mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
        return mapJson;
    }

    @RequestMapping("QueryAllRoleIdsService")
    public String queryAllRoleIds(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }

        List<Role> roles = roleService.getAllRoles();
        List<Integer> uids = new ArrayList<>();
        for (int i = 0; i < roles.size(); i++) {
            uids.add(roles.get(i).getId());
        }
        Map<String, Object> schema = new HashMap<String, Object>();
        schema.put("resultCode", "0");
        schema.put("roleIdList", uids);
        schema.put("message", "success");
        String mapJson = JacksonUtil.toJson(schema);
        mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
        return mapJson;
    }

    @RequestMapping("QueryRoleByIdService")
    public String queryRoleById(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }
        Map<String, Object> reqMap = (Map<String, Object>)checkResult.get("reqMap");
        String roleId = Objects.toString(reqMap.get("bimRid"));
        Role role = roleService.getRoleById(Integer.parseInt(roleId));
        Map<String, Object> schema = new HashMap<String, Object>();
        schema.put("bimRequestId", reqMap.get("bimRequestId"));
        schema.put("resultCode", "0");
        schema.put("role", role);
        schema.put("message", "success");
        String mapJson = JacksonUtil.toJson(schema);
        mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
        return mapJson;
    }

    @RequestMapping("QueryAllResourceIdsService")
    public String queryAllResourceIdsService(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }
        Map<String, Object> reqMap = (Map<String, Object>)checkResult.get("reqMap");
        String resourceType = Objects.toString(reqMap.get("resourceType"));
        if ("position".equals(resourceType)) {
            List<Position> allPositions = positionService.getAllPositions();
            List<Integer> uids = new ArrayList<>();
            for (int i = 0; i < allPositions.size(); i++) {
                uids.add(allPositions.get(i).getId());
            }
            Map<String, Object> schema = new HashMap<String, Object>();
            schema.put("resultCode", "0");
            schema.put("resourceIdList", uids);
            schema.put("message", "success");
            schema.put("bimRequestId", reqMap.get("bimRequestId"));
            String mapJson = JacksonUtil.toJson(schema);
            mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
            return mapJson;
        }
        return null;
    }

    @RequestMapping("QueryResourceByIdService")
    public String queryResourceByIdService(HttpServletRequest request) {
        Map<String, Object> checkResult = checkRequest(request);
        boolean checkPass = (boolean)checkResult.get("checkPass");
        if(!checkPass){
            return Objects.toString(checkResult.get("errorMsgStr"));
        }
        Map<String, Object> reqMap = (Map<String, Object>)checkResult.get("reqMap");
        String resourceType = Objects.toString(reqMap.get("resourceType"));
        String resourceId = Objects.toString(reqMap.get("resourceId"));
        if ("position".equals(resourceType)) {
            List<Position> allPositions = positionService.getAllPositions();
            Position position = null;
            for (int i = 0; i < allPositions.size(); i++) {
                if(allPositions.get(i).getId() == Integer.valueOf(resourceId)){
                    position = allPositions.get(i);
                    break;
                }
            }
            Map<String, Object> schema = new HashMap<String, Object>();
            schema.put("resultCode", "0");
            schema.put("resource", position);
            schema.put("message", "success");
            schema.put("bimRequestId", reqMap.get("bimRequestId"));
            String mapJson = JacksonUtil.toJson(schema);
            mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
            return mapJson;
        }
        return null;
    }
}
